'use strict';

const Controller = require('egg').Controller;

/**
 * 200=成功
 * 301-399=错误码 
 */
class UsersController extends Controller {
    /**
     * 登录
     * @returns 成功返回token
     */
    async login() {
        const { ctx, config, app } = this;
        let { code, key, login_name, password } = ctx.request.body;
        console.log("登录", { code, key, login_name, password });
        //验证图形验证码
        await ctx.service.auth.valiCode(code, key);

        password = await ctx.service.rsa.decrypt(password);
        let rs = await ctx.service.auth.verifyLogin({ login_name: login_name, password: password });
        let token;
        if (rs.code == 200) {
            //获取用户角色列表
            
            //生成token
            let content = {
                "login_name": rs.user.login_name,
                "nick_name": rs.user.nick_name,
                "avatar": rs.user.avatar,
            }
            token = await ctx.service.auth.genJwtoken(content);
            await ctx.service.redis.set(token, rs.user.user_id, config.auth.sysTokenTime);
            //如果需要返回菜单列表，在这里处理
            delete rs["user"];
        }
        ctx.body = {
            code: 200,
            msg: "成功",
            data: {
                token
            }
        };
    }

    /**
     * 登录
     * @returns base64
     */
    async getImgCode() {
        const { ctx } = this;
        ctx.body = {
            code: 200,
            msg: "成功",
            data: await ctx.service.auth.getImgCode()
        };
    }

    /**
     * @param 获取公钥，用于客户端加密
     * @return boolean
     */
    async getRsaPublicPem() {
        const { ctx } = this;
        let pem = await ctx.service.rsa.getNodeRSA();
        ctx.body = {
            "code": 200,
            "msg": "成功",
            "data": {
                publicPem: pem.publicPem
            }
        };
    }

    /**
     * 退出登录
     */
    async loginOut() {
        const { ctx } = this;
        const token = await ctx.request.headers.authorization;
        await ctx.service.auth.loginOut();
        ctx.body = {
            "code": 200,
            "msg": "安全退出",
            "data": {}
        };
    }

    /**
     * 通过token查询角色的menu
     */
    async getAuthentication() {
        const { ctx } = this;
        const token = await ctx.request.headers.authorization;
        let authentication = await ctx.service.auth.queryMenuByToken(token);
        ctx.body = {
            "code": 200,
            "msg": "成功",
            "data": authentication
        };
    }

}

module.exports = UsersController;